<template>
  <ChartContainer :title="title">
    <div class="chart" ref="chartRef"></div>
  </ChartContainer>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, toRefs } from 'vue';
import * as echarts from 'echarts';
import ChartContainer from './ChartContainer.vue';
import { getCategorySalesData } from '../../api/auth';


// 定义数据类型
interface CategorySalesItem {
  name: string;
  value: number;
}

defineOptions({
  name: 'LeftTop'
});

const props = defineProps({
  title: {
    type: String,
    default: '商品销售类别'
  }
});

const { title } = toRefs(props);

const chartRef = ref(null);
let chart: echarts.ECharts | null = null;
const categoryData = ref<CategorySalesItem[]>([]);

const fetchCategoryData = async () => {
  try {
    const res = await getCategorySalesData();
    if (res.data && res.data.code === 200 && res.data.data) {
      categoryData.value = res.data.data.map((item: any) => ({
        name: item.name,
        value: item.salesVolume || 0
      }));
    }
  } catch (error) {
    console.error('获取商品类别销量数据失败:', error);
  } finally {
    if (chart) {
      chart.dispose();
    }
    initChart();
  }
};

const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  if (categoryData.value.length === 0) {
    chart.setOption({
      title: {
        text: '暂无销售类别数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      }
    });
    return;
  }
  
  const option: echarts.EChartsOption = {
    grid: {
      top: '15%',
      left: '5%',
      right: '10%',
      bottom: '15%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        return `<strong>${params[0].name}</strong><br/>${params[0].marker} 销售数量: <strong>${params[0].value}</strong>`;
      },
      backgroundColor: 'rgba(0, 24, 57, 0.8)',
      borderColor: 'rgba(0, 183, 255, 0.4)',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    xAxis: {
      type: 'category',
      data: categoryData.value.map(item => item.name),
      axisLine: {
        lineStyle: {
          color: '#8392A5'
        }
      },
      axisLabel: {
        color: '#fff',
        interval: 0,
        rotate: 30,
        fontSize: 12,
        margin: 15,
        formatter: function(value: string) {
          if (value.length > 6) {
            return value.substring(0, 6) + '...';
          }
          return value;
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '销售数量',
      nameTextStyle: {
        color: '#fff',
        fontSize: 14,
        align: 'left',
        padding: [0, 0, 0, -15]
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#8392A5'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(131, 146, 165, 0.2)'
        },
        show: true
      },
      axisLabel: {
        color: '#fff',
        formatter: '{value}'
      }
    },
    series: [
      {
        data: categoryData.value.map((item, index) => {
          return {
            value: item.value,
            itemStyle: {
              color: getBarColor(index),
              borderRadius: [4, 4, 0, 0],
              shadowColor: 'rgba(0, 0, 0, 0.3)',
              shadowBlur: 5
            },
            label: {
              show: false
            }
          };
        }),
        type: 'bar',
        barWidth: '30%',
        showBackground: false,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 183, 255, 0.5)'
          }
        }
      }
    ],
    backgroundColor: 'transparent'
  };
  
  chart.setOption(option);
};

// 根据索引获取不同颜色
const getBarColor = (index: number) => {
  const colors = [
    'rgba(67, 97, 238, 0.8)',
    'rgba(247, 37, 133, 0.8)',
    'rgba(76, 201, 240, 0.8)',
    'rgba(114, 9, 183, 0.8)',
    'rgba(249, 65, 68, 0.8)',
    'rgba(144, 190, 109, 0.8)',
    'rgba(249, 199, 79, 0.8)'
  ];
  
  return colors[index % colors.length];
};

// 移除了 resizeChart 函数

onMounted(() => {
  fetchCategoryData().catch(error => {
    console.error('加载商品类别数据失败:', error);
    if (chart) {
      chart.dispose();
    }
    initChart();
  });
  // 移除了窗口大小变化监听
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
  }
  // 移除了窗口大小变化监听的移除代码
});

// 添加refresh方法供父组件调用
const refresh = async () => {
  await fetchCategoryData();
};

// 暴露refresh方法
defineExpose({
  refresh
});
</script> 